package com.admin.logging.aspect;

import cn.hutool.core.lang.Dict;
import com.admin.common.exception.MyBusinessException;
import com.admin.common.utils.IpUtil;
import com.admin.common.utils.StringUtils;
import com.admin.common.utils.ThrowableUtil;
import com.admin.component.web.RequestHolderUtil;
import com.admin.component.web.RequestUtil;
import com.admin.logging.annotation.Log;
import com.admin.logging.entity.SysLog;
import com.admin.logging.enums.LogTypeEnum;
import com.admin.logging.service.SysLogService;
import com.admin.oauth.util.LoginUserUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author sq-lan
 */
@Component
@Aspect
@Slf4j
public class LogAspect {

    private final SysLogService sysLogService;

    ThreadLocal<Long> currentTime = new ThreadLocal<>();

    public LogAspect(SysLogService sysLogService) {
        this.sysLogService = sysLogService;
    }

    /**
     * 配置切入点
     */
    @Pointcut("@annotation(com.admin.logging.annotation.Log)")
    public void logPointcut() {
        // 该方法无方法体,主要为了让同类中其他方法使用此切入点
    }

    /**
     * 配置环绕通知,使用在方法logPointcut()上注册的切入点
     *
     * @param joinPoint join point for advice
     */
    @Around("logPointcut()")
    public Object logAround(ProceedingJoinPoint joinPoint) throws Throwable {
        Object result;
        currentTime.set(System.currentTimeMillis());
        result = joinPoint.proceed();
        SysLog sysLog = genSysLog(LogTypeEnum.INFO.getValue(), joinPoint);
        sysLogService.add(sysLog);
        return result;
    }

    /**
     * 配置异常通知
     *
     * @param joinPoint join point for advice
     * @param e         exception
     */
    @AfterThrowing(pointcut = "logPointcut()", throwing = "e")
    public void logAfterThrowing(JoinPoint joinPoint, Throwable e) {
        int type = LogTypeEnum.ERROR.getValue();
        // 如果是自定义异常 type 为 警告
        if (e instanceof MyBusinessException) {
            type = LogTypeEnum.WARNING.getValue();
        }
        SysLog sysLog = genSysLog(type, joinPoint);
        if(type == LogTypeEnum.WARNING.getValue()) {
            sysLog.setExceptionDetail(e.getMessage());
        } else {
            sysLog.setExceptionDetail(new String(ThrowableUtil.getStackTrace(e).getBytes()));
        }
        sysLogService.add(sysLog);
    }

    private SysLog genSysLog(int logType, JoinPoint joinPoint) {
        long time = System.currentTimeMillis() - currentTime.get();
        currentTime.remove();
        SysLog sysLog = new SysLog();
        sysLog.setTime(time);
        sysLog.setLogType(logType);

        HttpServletRequest request = RequestHolderUtil.getHttpServletRequest();
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        Log aopLog = method.getAnnotation(Log.class);

        // 方法路径
        String methodName = joinPoint.getTarget().getClass().getName() + "." + signature.getName() + "()";

        sysLog.setOperateType(aopLog.operateType().getCode());
        sysLog.setModule(aopLog.module());
        // 描述
        sysLog.setDescription(aopLog.description());

        sysLog.setRequestIp(RequestUtil.getIp(request));
        sysLog.setAddress(IpUtil.getCityInfo(sysLog.getRequestIp()));
        sysLog.setMethod(methodName);
        sysLog.setParams(getParameter(method, joinPoint.getArgs()));
        // 记录登录用户，隐藏密码信息
        if ("login".equals(signature.getName()) && StringUtils.isNotEmpty(sysLog.getParams())) {
            JSONObject obj = JSON.parseObject(sysLog.getParams());
            sysLog.setUsername(obj.getString("username"));
            sysLog.setParams(JSON.toJSONString(Dict.create().set("username", sysLog.getUsername())));
        } else {
            sysLog.setUsername(LoginUserUtil.userName());
        }
        sysLog.setBrowser(RequestUtil.getBrowser(request));

        return sysLog;
    }

    /**
     * 根据方法和传入的参数获取请求参数
     */
    private String getParameter(Method method, Object[] args) {
        List<Object> argList = new ArrayList<>();
        Parameter[] parameters = method.getParameters();
        for (int i = 0; i < parameters.length; i++) {
            // 过滤掉不能序列化的类型: MultiPartFile
            if (args[i] instanceof MultipartFile) {
                continue;
            }
            //将RequestBody注解修饰的参数作为请求参数
            RequestBody requestBody = parameters[i].getAnnotation(RequestBody.class);
            if (requestBody != null) {
                argList.add(args[i]);
            }
            //将RequestParam注解修饰的参数作为请求参数
            RequestParam requestParam = parameters[i].getAnnotation(RequestParam.class);
            if (requestParam != null) {
                Map<String, Object> map = new HashMap<>(2);
                String key = parameters[i].getName();
                if (!StringUtils.isEmpty(requestParam.value())) {
                    key = requestParam.value();
                }
                map.put(key, args[i]);
                argList.add(map);
            }
        }
        if (argList.isEmpty()) {
            return "";
        }
        return argList.size() == 1 ? JSON.toJSONString(argList.get(0)) : JSON.toJSONString(argList);
    }

}
